/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.devmng.service;

import com.fasterxml.jackson.databind.JavaType;
import com.thinkgem.jeesite.common.exception.MobileApiException;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.service.ServiceException;
import com.thinkgem.jeesite.common.utils.BeanUtilEx;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.devmng.dao.TaskDelayApplyLogDao;
import com.thinkgem.jeesite.modules.devmng.dao.TaskMainDao;
import com.thinkgem.jeesite.modules.devmng.entity.*;
import com.thinkgem.jeesite.modules.devmng.vo.*;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import freemarker.template.SimpleDate;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 任务Service
 *
 * @author panda
 * @version 2017-12-04
 */
@Service
@Transactional(readOnly = true)
public class TaskMainService extends CrudService<TaskMainDao, TaskMain> {

    @Autowired
    private TaskDeviceDevchkItemService taskDeviceDevchkItemService;

    @Autowired
    private DeviceMainService deviceMainService;

    @Autowired
    private DevchkItemService devchkItemService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private TaskDetailService taskDetailService;

    @Autowired
    private DevchkItemAnswerService devchkItemAnswerService;

    @Autowired
    private TaskExecRecordService taskExecRecordService;

    @Autowired
    private TaskDelayApplyLogService taskDelayApplyLogService;

    @Autowired
    private TaskExecRecordAttaService taskExecRecordAttaService;

    @Transactional(readOnly = false)
    public void sign(TaskMainSignRequest request) {
        TaskMain taskMain = this.get(request.getId());
        if (TaskMain.Status.PENDING.name().equals(taskMain.getTaskStatus())) {
            throw new MobileApiException("任务正在审批中");
        }
        if (!TaskMain.Status.OPEN.name().equals(taskMain.getTaskStatus())) {
            throw new MobileApiException("任务已签收");
        }
        taskMain.setStartDate(new Date());
        taskMain.setTaskStatus(TaskMain.Status.PROCESSING.name());
        taskMain.setStationDutyPerson(request.getStationDutyPerson());
        taskMain.setStationAttendant(request.getStationAttendant());
        taskMain.setNetDispatcher(request.getNetDispatcher());
        taskMain.setLon(request.getLon());
        taskMain.setLat(request.getLat());
        taskMain.setWeatherCondition(request.getWeatherCondition());
        super.save(taskMain);
    }

    @Transactional(readOnly = false)
    public void applyForDelay(ApplyForDelayRequest request) {
        if (request.getDelayTaskStart() == null || request.getDelayTaskEnd() == null) {
            throw new MobileApiException("请输入延迟执行的时间");
        }
        if (StringUtils.isEmpty(request.getApplyNote())) {
            throw new MobileApiException("请填写延迟理由");
        }
        TaskMain taskMain = this.get(request.getId());
        if (taskMain == null) {
            throw new MobileApiException("找不到任务");
        }

        TaskDelayApplyLog log = new TaskDelayApplyLog();
        log.setOriginalTaskId(request.getId());
        List<TaskDelayApplyLog> logList = taskDelayApplyLogService.findList(log);
        boolean pendingFlag = false;
        boolean closeFlag = false;
        for (TaskDelayApplyLog taskDelayApplyLog : logList) {
            if (TaskDelayApplyLog.Status.PENDING.name().equals(taskDelayApplyLog.getStatus())) {
                pendingFlag = true;
            }
            if (TaskDelayApplyLog.Status.CLOSE.name().equals(taskDelayApplyLog.getStatus())) {
                closeFlag = true;
            }
        }
        if (pendingFlag) {
            throw new MobileApiException("任务正在审批中，请耐心等待！");
        }
        if (closeFlag) {
            throw new MobileApiException("任务已经审批通过！");
        }

        taskMain.setTaskStatus(TaskMain.Status.PENDING.name());
        super.save(taskMain);


        addNewLog(request, taskMain);
    }

    private void addNewLog(ApplyForDelayRequest request, TaskMain taskMain) {
        TaskDelayApplyLog log = new TaskDelayApplyLog();
        log.setApplyContent(request.getApplyNote());
        log.setApplyStart(request.getDelayTaskStart());
        log.setApplyStop(request.getDelayTaskEnd());
        log.setOriginalTaskId(request.getId());
        log.setOriginalTaskName(taskMain.getTaskTitle());
        log.setOriginalStart(taskMain.getTaskStart());
        log.setOriginalEnd(taskMain.getTaskEnd());
        log.setStatus(TaskDelayApplyLog.Status.PENDING.name());
        taskDelayApplyLogService.save(log);
    }

    @Transactional(readOnly = false)
    public void access(TaskMainAccessRequest request) {
        TaskMain taskMain = this.get(request.getId());
        taskMain.setDutyPersonInfo(request.getDutyPersonInfo());
        taskMain.setDutyPersonRemarks(request.getDutyPersonRemarks());
        super.save(taskMain);
    }

    public TaskMain get(String id) {
        TaskMain taskMain = super.get(id);
        return taskMain;
    }

    public TaskMainResponse getTaskMainResponse(String id) {
        TaskMainResponse taskMainResponse = new TaskMainResponse();
        TaskMain taskMain = super.get(id);
        if (taskMain != null) {
            BeanUtilEx.copyProperties(taskMainResponse, taskMain);
            // 设置任务的设备
            List<DeviceMain> deviceMainList = deviceMainService.findListByTaskMainId(taskMain.getId());

            TaskDeviceDevchkItem taskDeviceDevchkItem = new TaskDeviceDevchkItem();
            taskDeviceDevchkItem.setTaskMainId(taskMain.getId());
            List<TaskDeviceDevchkItem> taskDeviceDevchkItemList = taskDeviceDevchkItemService.findList(taskDeviceDevchkItem);
            Map<String, List<TaskDeviceDevchkItem>> id2ObjMap = new HashedMap();
            for (TaskDeviceDevchkItem item : taskDeviceDevchkItemList) {
                List<TaskDeviceDevchkItem> itemList = id2ObjMap.get(item.getDeviceMainId());
                if (itemList == null) {
                    itemList = new ArrayList<TaskDeviceDevchkItem>();
                    id2ObjMap.put(item.getDeviceMainId(), itemList);
                }
                itemList.add(item);
            }
            List<DeviceMainWithStatus> deviceMainWithStatusList = new ArrayList<DeviceMainWithStatus>();
            for (DeviceMain deviceMain : deviceMainList) {
                DeviceMainWithStatus deviceMainWithStatus = new DeviceMainWithStatus();
                BeanUtilEx.copyProperties(deviceMainWithStatus, deviceMain);
                List<TaskDeviceDevchkItem> itemList = id2ObjMap.get(deviceMain.getId());
                String status = caculateStatus(itemList);
                deviceMainWithStatus.setStatus(status);
                deviceMainWithStatusList.add(deviceMainWithStatus);
            }
            taskMainResponse.setDeviceMainList(deviceMainWithStatusList);
            taskMainResponse.setDelayFlag(getDelayFlag(taskMain));
        }
        return taskMainResponse;
    }

    private String getDelayFlag(TaskMain taskMain) {
        Date taskEnd = taskMain.getTaskEnd();
        if (!StringUtils.equals(taskMain.getTaskStatus(), TaskMain.Status.OPEN.name())) {
            return "N";
        }
        if (taskEnd == null) {
            return "N";
        }
        if (new Date().compareTo(taskEnd) > 0) {
            return "Y";
        }
        return "N";
    }

    private String caculateStatus(List<TaskDeviceDevchkItem> itemList) {
        if (itemList == null || itemList.size() == 0) {
            return TaskDeviceDevchkItem.Status.CLOSE.name();
        }
        for (TaskDeviceDevchkItem item : itemList) {
            if (TaskDeviceDevchkItem.Status.OPEN.name().equals(item.getStatus())) {
                return TaskDeviceDevchkItem.Status.OPEN.name();
            }
        }
        return TaskDeviceDevchkItem.Status.CLOSE.name();
    }

    public List<TaskMain> findList(TaskMain taskMain) {
        return super.findList(taskMain);
    }

    public Page<TaskMain> findPage(Page<TaskMain> page, TaskMain taskMain) {
        return super.findPage(page, taskMain);
    }

    @Transactional(readOnly = false)
    public void saveSuper(TaskMain taskMain) {
        super.save(taskMain);
    }

    @Transactional(readOnly = false)
    public void save(TaskMain taskMain, String deviceInfoJsonInput) {
        if (StringUtils.isNotEmpty(taskMain.getId())) {
            if (!TaskMain.Status.OPEN.name().equals(taskMain.getTaskStatus())) {
                throw new ServiceException("任务已经开始，不能进行修改！");
            }
        }
        User user = systemService.getUser(taskMain.getTaskOperator().getId());
        taskMain.setSysOffice(new Office(user.getOffice().getId()));
        taskMain.setTaskStatus(TaskMain.Status.OPEN.name());
        super.save(taskMain);
        // 删除旧数据
        taskDeviceDevchkItemService.deleteByTaskMainId(taskMain.getId());
        taskDetailService.deleteByTaskMainId(taskMain.getId());
        // 处理新数据
//        String deviceInfoJson = StringEscapeUtils.unescapeJson(StringEscapeUtils.unescapeHtml4(taskMain.getDeviceInfoJson()));
        String deviceInfoJson = StringEscapeUtils.unescapeHtml4(deviceInfoJsonInput);
        JavaType javaType = JsonMapper.getInstance().createCollectionType(ArrayList.class, TaskDetail.class);
        List<TaskDetail> taskDetailList = JsonMapper.getInstance().fromJson(deviceInfoJson, javaType);
        for (TaskDetail taskDetail : taskDetailList) {
            taskDetail.setTaskMainId(taskMain.getId());
            taskDetailService.save(taskDetail);
        }

        int devchkItemCount = 0;
        // 遍历任务所有的设备
        for (TaskDetail taskDetail : taskDetailList) {
            // 获取设备的检修项信息
            DevchkItem queryDevchkItem = new DevchkItem();
            queryDevchkItem.setDeviceMain(new DeviceMain(taskDetail.getDeviceMainId()));
            List<DevchkItem> devchkItemList = devchkItemService.findList(queryDevchkItem);

            // 增加任务、设备以及检修项的关联关系
            for (DevchkItem devchkItem : devchkItemList) {
                boolean match = DevchkItem.CheckPeriod.Y.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getYearFlag().equals("Y")
                        || DevchkItem.CheckPeriod.M.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getMonthFlag().equals("Y")
                        || DevchkItem.CheckPeriod.HY.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getHalfYearFlag().equals("Y")
                        || DevchkItem.CheckPeriod.Q.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getQuarterFlag().equals("Y");
                if (!match) {
                    continue;
                }
                devchkItemCount += 1;
                TaskDeviceDevchkItem taskDeviceDevchkItem = new TaskDeviceDevchkItem();
                taskDeviceDevchkItem.setDeviceMainId(taskDetail.getDeviceMainId());
                taskDeviceDevchkItem.setTaskMainId(taskMain.getId());
                taskDeviceDevchkItem.setDevchkItemId(devchkItem.getId());
                taskDeviceDevchkItem.setStatus(TaskDeviceDevchkItem.Status.OPEN.name());
                taskDeviceDevchkItemService.save(taskDeviceDevchkItem);
            }
        }
        if (devchkItemCount == 0) {
            throw new ServiceException("没有发现设备的检修项！");
        }
    }

    @Transactional(readOnly = false)
    public void save(TaskMain taskMain) {
        Date date = new Date();
        if (StringUtils.isNotEmpty(taskMain.getId())) {
            if (!TaskMain.Status.OPEN.name().equals(taskMain.getTaskStatus())) {
                throw new ServiceException("任务已经开始，不能进行修改！");
            }
        }
        //转成数组
        String deviceIds = "";
        String deviceNames = "";
       //获取部门下的设备信息
        List<DeviceMain> officeList = deviceMainService.findListIdBySysOffice(taskMain.getSysOffice().getId());
        for (DeviceMain dm : officeList) {
            deviceIds += dm.getId() + ",";
            deviceNames += dm.getDeviceName() + "(" + dm.getDeviceUser().getName() + ")" + ",";
        }
        String[] idsList = deviceIds.split(",");
        String[] namesList = deviceNames.split(",");
        String taskType = (String) taskMain.getTaskType();
        String monthFlag = "N";
        String quarterFlag = "N";
        String halfYearFlag = "N";
        String yearFlag = "N";
        String taskTitle = "";
        switch (taskType) {
            case "M":
                monthFlag = "Y";
                taskTitle = taskMain.getSysOffice().getName() + "月度计划";
                break;
            case "Q":
                quarterFlag = "Y";
                taskTitle = taskMain.getSysOffice().getName() + "季度度计划";
                break;
            case "HY":
                halfYearFlag = "Y";
                taskTitle = taskMain.getSysOffice().getName() + "半年度计划";
                break;
            case "Y":
                yearFlag = "Y";
                taskTitle = taskMain.getSysOffice().getName() + "年度度计划";
                break;
        }

        taskMain.setTaskTitle(taskTitle + " (" +(new SimpleDateFormat("MM")).format(date)  + "月)");
        User user = systemService.getUser(taskMain.getTaskOperator().getId());
        taskMain.setSysOffice(new Office(user.getOffice().getId()));
        taskMain.setTaskStatus(TaskMain.Status.OPEN.name());
        taskMain.setTaskOperator(user);
        //任务保存
        super.save(taskMain);
        // 删除旧数据
        taskDeviceDevchkItemService.deleteByTaskMainId(taskMain.getId());
        taskDetailService.deleteByTaskMainId(taskMain.getId());
        // 处理新数据

        List<TaskDetail> taskDetailList = new ArrayList<>();

        for (int i = 0; i < idsList.length; i++) {
            TaskDetail td = new TaskDetail();
            td.setDeviceMainId(idsList[i]);
            td.setDeviceName(namesList[i]);
            td.setTaskMainId(taskMain.getId());
            td.setMonthFlag(monthFlag);
            td.setQuarterFlag(quarterFlag);
            td.setHalfYearFlag(halfYearFlag);
            td.setYearFlag(yearFlag);
            taskDetailList.add(td);
            taskDetailService.save(td);

        }

        int devchkItemCount = 0;
        // 遍历任务所有的设备
        for (TaskDetail taskDetail : taskDetailList) {
            // 获取设备的检修项信息
            DevchkItem queryDevchkItem = new DevchkItem();
            queryDevchkItem.setDeviceMain(new DeviceMain(taskDetail.getDeviceMainId()));
            List<DevchkItem> devchkItemList = devchkItemService.findList(queryDevchkItem);

            // 增加任务、设备以及检修项的关联关系
            for (DevchkItem devchkItem : devchkItemList) {
                boolean match = DevchkItem.CheckPeriod.Y.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getYearFlag().equals("Y")
                        || DevchkItem.CheckPeriod.M.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getMonthFlag().equals("Y")
                        || DevchkItem.CheckPeriod.HY.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getHalfYearFlag().equals("Y")
                        || DevchkItem.CheckPeriod.Q.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getQuarterFlag().equals("Y");
                if (!match) {
                    continue;
                }
                devchkItemCount += 1;
                TaskDeviceDevchkItem taskDeviceDevchkItem = new TaskDeviceDevchkItem();
                taskDeviceDevchkItem.setDeviceMainId(taskDetail.getDeviceMainId());
                taskDeviceDevchkItem.setTaskMainId(taskMain.getId());
                taskDeviceDevchkItem.setDevchkItemId(devchkItem.getId());
                taskDeviceDevchkItem.setStatus(TaskDeviceDevchkItem.Status.OPEN.name());
                taskDeviceDevchkItemService.save(taskDeviceDevchkItem);
            }
        }
        if (devchkItemCount == 0) {
            throw new ServiceException("没有发现设备的检修项！");
        }
    }

    @Transactional
    public TaskMain copy(TaskMain taskMain) {
        if (!TaskMain.Status.OPEN.name().equals(taskMain.getTaskStatus())
                && !TaskMain.Status.PENDING.name().equals(taskMain.getTaskStatus())) {
            throw new ServiceException("任务已经开始，不能进行复制操作！");
        }
        TaskDetail taskDetailQuery = new TaskDetail();
        taskDetailQuery.setTaskMainId(taskMain.getId());
        List<TaskDetail> taskDetailList = taskDetailService.findList(taskDetailQuery);
        // 复制任务
        User user = systemService.getUser(taskMain.getTaskOperator().getId());
        taskMain.setSysOffice(new Office(user.getOffice().getId()));
        taskMain.setTaskStatus(TaskMain.Status.OPEN.name());
        taskMain.setId(null);
        super.save(taskMain);
        // 复制任务子数据
        List<TaskDetail> copyTaskDetailList = new ArrayList<>();
        for (TaskDetail taskDetail : taskDetailList) {
            TaskDetail td = new TaskDetail();
            td.setDeviceMainId(taskDetail.getDeviceMainId());
            td.setDeviceName(taskDetail.getDeviceName());
            td.setTaskMainId(taskMain.getId());
            td.setMonthFlag(taskDetail.getMonthFlag());
            td.setQuarterFlag(taskDetail.getQuarterFlag());
            td.setHalfYearFlag(taskDetail.getHalfYearFlag());
            td.setYearFlag(taskDetail.getYearFlag());
            taskDetailService.save(td);
            copyTaskDetailList.add(td);
        }
        int devchkItemCount = 0;
        // 遍历任务所有的设备
        for (TaskDetail taskDetail : copyTaskDetailList) {
            // 获取设备的检修项信息
            DevchkItem queryDevchkItem = new DevchkItem();
            queryDevchkItem.setDeviceMain(new DeviceMain(taskDetail.getDeviceMainId()));
            List<DevchkItem> devchkItemList = devchkItemService.findList(queryDevchkItem);

            // 增加任务、设备以及检修项的关联关系
            for (DevchkItem devchkItem : devchkItemList) {
                boolean match = DevchkItem.CheckPeriod.Y.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getYearFlag().equals("Y")
                        || DevchkItem.CheckPeriod.M.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getMonthFlag().equals("Y")
                        || DevchkItem.CheckPeriod.HY.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getHalfYearFlag().equals("Y")
                        || DevchkItem.CheckPeriod.Q.name().equals(devchkItem.getCheckPeriod()) && taskDetail.getQuarterFlag().equals("Y");
                if (!match) {
                    continue;
                }
                devchkItemCount += 1;
                TaskDeviceDevchkItem taskDeviceDevchkItem = new TaskDeviceDevchkItem();
                taskDeviceDevchkItem.setDeviceMainId(taskDetail.getDeviceMainId());
                taskDeviceDevchkItem.setTaskMainId(taskMain.getId());
                taskDeviceDevchkItem.setDevchkItemId(devchkItem.getId());
                taskDeviceDevchkItem.setStatus(TaskDeviceDevchkItem.Status.OPEN.name());
                taskDeviceDevchkItemService.save(taskDeviceDevchkItem);
            }
        }
        if (devchkItemCount == 0) {
            throw new ServiceException("没有发现设备的检修项！");
        }
        return taskMain;
    }

    @Transactional(readOnly = false)
    public void delete(TaskMain taskMain) {
        super.delete(taskMain);
    }


    public Page<TaskMainExecDetailResponse> listTaskMainExecDetail(Page<TaskMainExecDetailResponse> page,
                                                                   TaskMainExecDetailRequest request,
                                                                   String taskMainId) {
        request.setId(taskMainId);
        request.setPage(page);
        List<TaskMainExecDetailResponse> taskExecDetail = dao.findTaskExecDetail(request);
        List<TaskMainExecDetailResponse> temp = new ArrayList<>();
        List<String> devchkItemIds = new ArrayList<>();
        List<String> taskMainIds = new ArrayList<>();
       //ID加入列表中
        for (TaskMainExecDetailResponse res : taskExecDetail) {
            devchkItemIds.add(res.getDevchkItemId());
            taskMainIds.add(res.getTaskMainId());
            res.setSysOfficeName(deviceMainService.get(res.getDeviceMainId()).getSysOffice().getName());
            res.setDeviceTypeName(deviceMainService.get(res.getDeviceMainId()).getDeviceType().getName());
        }
        //取出所有回答项
        List<DevchkItemAnswerResponse> devchkItemAnswerResponseList = devchkItemAnswerService.listByDevchkItemIds(devchkItemIds);
        Map<String, DevchkItemAnswerResponse> key2DevchkItemAnswerResponseMap = new HashMap<>();
        for (DevchkItemAnswerResponse res : devchkItemAnswerResponseList) {
            key2DevchkItemAnswerResponseMap.put(res.getDevchkItemId() + "_" + res.getDevchkAnswerId(), res);
        }
        List<TaskExecRecord> taskExecRecords = taskExecRecordService.listByTaskMainIds(taskMainIds);
        Map<String, TaskExecRecord> key2TaskExecRecordMap = new HashMap<>();
        for (TaskExecRecord taskExecRecord : taskExecRecords) {
            key2TaskExecRecordMap.put(taskExecRecord.getTaskMainId() + "_" + taskExecRecord.getDevchkItemId() + "_" + taskExecRecord.getDevchkAnswerId(), taskExecRecord);
        }
		
        TaskExecRecordAtta query = new TaskExecRecordAtta();
        List<TaskExecRecordAtta> list = taskExecRecordAttaService.findList(query);

        for (TaskMainExecDetailResponse res : taskExecDetail) {
            // 设置正常与不正常信息 1
            TaskExecRecord taskExecRecord = key2TaskExecRecordMap.get(res.getTaskMainId() + "_" + res.getDevchkItemId() + "_" + "1");
            if (taskExecRecord != null) {
                res.setRecordCreateDate(taskExecRecord.getCreateDate());
                res.setRecordUpdateDate(taskExecRecord.getUpdateDate());
                if ("1".equals(taskExecRecord.getDevchkAnswerItemId())) {
                    res.setNormalDesc("正常");
                } else {
                    res.setNormalDesc("不正常");
                }
            }
            // 设置备注信息 3
            taskExecRecord = key2TaskExecRecordMap.get(res.getTaskMainId() + "_" + res.getDevchkItemId() + "_" + "3");
            if (taskExecRecord != null) {
                res.setRemarks(taskExecRecord.getTextContent());
            }
            // 获取测量值 2，5-14
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "2");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "5");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "6");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "7");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "8");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "9");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "10");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "11");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "12");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "13");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "14");

			//判断是否有Url
            query.setTaskMainId(res.getTaskMainId());
            query.setDeviceMainId(res.getDeviceMainId());
            query.setDevchkItemId(res.getDevchkItemId());
            list = taskExecRecordAttaService.findList(query);
            if (list.size() != 0) {
                res.setFlagUrl("Y");
            }

        }
        page.setList(taskExecDetail);
        return page;
    }

    public Page<TaskMainExecDetailResponse> listTaskMainExecDetail(Page<TaskMainExecDetailResponse> page, TaskMainExecDetailRequest request) {
        request.setPage(page);
        List<TaskMainExecDetailResponse> taskExecDetail = dao.findTaskExecDetail(request);

        List<String> devchkItemIds = new ArrayList<>();
        List<String> taskMainIds = new ArrayList<>();
        for (TaskMainExecDetailResponse res : taskExecDetail) {
            devchkItemIds.add(res.getDevchkItemId());
            taskMainIds.add(res.getTaskMainId());
        }
        List<DevchkItemAnswerResponse> devchkItemAnswerResponseList = devchkItemAnswerService.listByDevchkItemIds(devchkItemIds);
        Map<String, DevchkItemAnswerResponse> key2DevchkItemAnswerResponseMap = new HashMap<>();
        for (DevchkItemAnswerResponse res : devchkItemAnswerResponseList) {
            key2DevchkItemAnswerResponseMap.put(res.getDevchkItemId() + "_" + res.getDevchkAnswerId(), res);
        }
        List<TaskExecRecord> taskExecRecords = taskExecRecordService.listByTaskMainIds(taskMainIds);
        Map<String, TaskExecRecord> key2TaskExecRecordMap = new HashMap<>();
        for (TaskExecRecord taskExecRecord : taskExecRecords) {
            key2TaskExecRecordMap.put(taskExecRecord.getTaskMainId() + "_" + taskExecRecord.getDevchkItemId() + "_" + taskExecRecord.getDevchkAnswerId(), taskExecRecord);
        }

        for (TaskMainExecDetailResponse res : taskExecDetail) {
            // 设置正常与不正常信息 1
            TaskExecRecord taskExecRecord = key2TaskExecRecordMap.get(res.getTaskMainId() + "_" + res.getDevchkItemId() + "_" + "1");
            if (taskExecRecord != null) {
                if ("1".equals(taskExecRecord.getDevchkAnswerItemId())) {
                    res.setNormalDesc("正常");
                } else {
                    res.setNormalDesc("不正常");
                }
            }
            // 设置备注信息 3
            taskExecRecord = key2TaskExecRecordMap.get(res.getTaskMainId() + "_" + res.getDevchkItemId() + "_" + "3");
            if (taskExecRecord != null) {
                res.setRemarks(taskExecRecord.getTextContent());
            }
            // 获取测量值 2，5-14
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "2");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "5");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "6");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "7");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "8");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "9");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "10");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "11");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "12");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "13");
            formatMeatureDesc(key2DevchkItemAnswerResponseMap, key2TaskExecRecordMap, res, "14");

        }
        page.setList(taskExecDetail);
        return page;
    }

    private void formatMeatureDesc(Map<String, DevchkItemAnswerResponse> key2DevchkItemAnswerResponseMap,
                                   Map<String, TaskExecRecord> key2TaskExecRecordMap,
                                   TaskMainExecDetailResponse res,
                                   String devchkAnswerId) {
        TaskExecRecord taskExecRecord = key2TaskExecRecordMap.get(res.getTaskMainId() + "_" + res.getDevchkItemId() + "_" + devchkAnswerId);
        if (taskExecRecord != null) {
            DevchkItemAnswerResponse devchkItemAnswerResponse = key2DevchkItemAnswerResponseMap.get(taskExecRecord.getDevchkItemId() + "_" + devchkAnswerId);
            if (devchkItemAnswerResponse != null) {
                res.setMeatureDesc(res.getMeatureDesc() + formatNumberInput(devchkItemAnswerResponse.getContentDesc(), devchkItemAnswerResponse.getUnitCode(), taskExecRecord.getNumContent()));
            } else {
                res.setMeatureDesc(res.getMeatureDesc() + formatNumberInput(taskExecRecord.getNumContent()));
            }
        }
    }

    private String formatNumberInput(String contentDesc, String unitCode, BigDecimal value) {
        if (value == null) {
            String.format("<div>%s: %s</div>", contentDesc, unitCode);
        }
        DecimalFormat df = new DecimalFormat("#.######");
        return String.format("<div>%s:%s %s</div>", contentDesc, df.format(value), unitCode);
    }

    private String formatNumberInput(BigDecimal value) {
        if (value == null) {
            return "";
        }
        DecimalFormat df = new DecimalFormat("#.######");
        return String.format("<div>%s</div>", df.format(value));
    }

    @Transactional(readOnly = false)
    public void pass(String id) {
        TaskDelayApplyLog taskDelayApplyLog = taskDelayApplyLogService.get(id);
        if (!TaskDelayApplyLog.Status.PENDING.name().equals(taskDelayApplyLog.getStatus())) {
            throw new ServiceException("该申请已经被操作！");
        }
        TaskMain taskMain = this.get(taskDelayApplyLog.getOriginalTaskId());
        if (taskMain == null) {
            throw new ServiceException("找不到申请的任务数据！");
        }
        taskMain.setTaskStart(taskDelayApplyLog.getApplyStart());
        taskMain.setTaskEnd(taskDelayApplyLog.getApplyStop());
        TaskMain newTaskMain = this.copy(taskMain);

        taskDelayApplyLog.setStatus(TaskDelayApplyLog.Status.CLOSE.name());
        taskDelayApplyLog.setNewTaskId(newTaskMain.getId());
        taskDelayApplyLogService.save(taskDelayApplyLog);

        TaskMain oldTaskMain = this.get(taskDelayApplyLog.getOriginalTaskId());
        this.delete(oldTaskMain);
    }

    @Transactional(readOnly = false)
    public void reject(String id) {
        TaskDelayApplyLog taskDelayApplyLog = taskDelayApplyLogService.get(id);
        if (!TaskDelayApplyLog.Status.PENDING.name().equals(taskDelayApplyLog.getStatus())) {
            throw new ServiceException("该申请已经被操作！");
        }
        TaskMain taskMain = this.get(taskDelayApplyLog.getOriginalTaskId());
        if (taskMain == null) {
            throw new ServiceException("找不到申请的任务数据！");
        }
        taskDelayApplyLog.setStatus(TaskDelayApplyLog.Status.REJECT.name());
        taskDelayApplyLogService.save(taskDelayApplyLog);
    }

}